set(libs "${libs_to_build}")

# Process the visualizer module first if enabled
if(visualizer IN_LIST libs)
  if(${ENABLE_VISUALIZER})
    message(STATUS "Processing src/visualizer")
    add_subdirectory(visualizer)
  endif()
  list(REMOVE_ITEM libs visualizer)
endif()

# Process subdirectories
foreach(libname ${libs})
  if(EXISTS ${PROJECT_SOURCE_DIR}/src/${libname}/CMakeLists.txt)
    message(STATUS "Processing src/${libname}")
    add_subdirectory(${libname})
  else()
    message(${HIGHLIGHTED_STATUS}
            "Skipping src/${libname}: it does not contain a CMakeLists.txt file"
    )
  endif()
endforeach()

# Prevents link errors due to symbol collisions if the same library is linked
# multiple times
list(REMOVE_DUPLICATES dy1-external-libs)

# Build the lib-dy1-static (dy1.x-static-buildtype.a/.lib) with all sublibraries
if(${DY1_STATIC})
  add_library(
    ${lib-dy1-static} STATIC ${PROJECT_SOURCE_DIR}/build-support/empty.cc
                             "${lib-dy1-static-objs}"
  )

  # Replace shared library suffix and check if static version exists before
  # linking
  set(dy1-external-static-libs)
  foreach(sharedlib ${dy1-external-libs})
    if(NOT (${sharedlib} MATCHES ".so"))
      list(APPEND dy1-external-static-libs ${sharedlib})
      continue()
    endif()

    string(REPLACE ".so" ".a" output ${sharedlib})
    if(EXISTS ${output})
      list(APPEND dy1-external-static-libs ${output})
    else()
      message(
        FATAL_ERROR "Static library version of ${sharedlib} was not found"
      )
    endif()
  endforeach()

  # Required by some static libraries, such as sqlite, for some odd reason
  if(LINUX)
    list(APPEND dy1-external-static-libs -ldl)
  endif()

  target_link_libraries(
    ${lib-dy1-static} ${STATIC_LINK_FLAGS} ${LIB_AS_NEEDED_PRE_STATIC}
    ${dy1-external-static-libs} ${LIB_AS_NEEDED_POST_STATIC}
  )
  if(${DY1_CLANG_TIMETRACE})
    add_dependencies(timeTraceReport ${lib-dy1-static})
  endif()
endif()

# Build the lib-dy1 (dy1.x-monolib-buildtype.dll/.dylib/.so) with all
# sublibraries
if(${DY1_MONOLIB})
  add_library(
    ${lib-dy1-monolib} SHARED ${PROJECT_SOURCE_DIR}/build-support/empty.cc
                              "${lib-dy1-static-objs}"
  )
  set_target_properties(
    ${lib-dy1-monolib}
    PROPERTIES INTERPROCEDURAL_OPTIMIZATION TRUE
               RUNTIME_OUTPUT_DIRECTORY
               ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} # set output directory for DLLs
  )
  target_link_libraries(
    ${lib-dy1-monolib} ${LIB_AS_NEEDED_PRE} ${dy1-external-libs}
    ${LIB_AS_NEEDED_POST}
  )
  if(${DY1_CLANG_TIMETRACE})
    add_dependencies(timeTraceReport ${lib-dy1-monolib})
  endif()
endif()

if(${DY1_FETCH_OPTIONAL_COMPONENTS})
  add_dependency_to_optional_modules_dependencies()
endif()
